package com.imooc.miaosha.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 模块描述: <br>
 * (类型转换)
 *
 * @Author: Mr. xyb
 * @Date: 2019/4/24 13:21
 * @since: 1.8.0
 * @version: 1.0.0
 */
public class TypeConversionUtils {

    /**
     * bean对象转为字符串
     *
     * @param value
     * @param <T>
     * @return
     */
    public static <T> String beanToString(T value) {
        if (value == null) {
            return null;
        }
        Class<?> clazz = value.getClass();
        if (clazz == int.class || clazz == Integer.class) {
            return value + "";
        } else if (clazz == long.class || clazz == Long.class) {
            return value + "";
        } else if (clazz == String.class) {
            return (String) value;
        } else {
            return JSON.toJSONString(value);
        }
    }

    /**
     * 将字符串转换为bean
     *
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T stringToBean(String str, Class<T> clazz) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        if (clazz == int.class || clazz == Integer.class) {
            return (T) Integer.valueOf(str);
        } else if (clazz == long.class || clazz == Long.class) {
            return (T) Long.valueOf(str);
        } else if (clazz == String.class) {
            return (T) str;
        } else {
            JSONObject jsonObject = JSON.parseObject(str);
            T t = JSON.toJavaObject(jsonObject, clazz);
            return t;
        }
    }
}
